package com.eddie.hhcook.utils;

import java.io.File;
import java.math.BigDecimal;

/**
 * Created by hy on 2015/5/4.
 */
public class CacheUtils {
    public static void deleteFilesByDirectory(File directory) {
        try {
            if (directory != null && directory.exists() && directory.isDirectory()) {
//                Log.i("usableSpace==", "usableSpace====");
                for (File item : directory.listFiles()) {
                    deleteFilesByDirectory(item);
//                    Log.i("usableSpace==", "usableSpace====itemlength before" + item.length());
                    item.delete();
//                    Log.i("usableSpace==", "usableSpace====itemlength after=================================" + item.length());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "B";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(1, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(1, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(1, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(1, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }

    public static long getFilesSize(File directory) {
        long size = 0;
        try {
            if (directory != null && directory.exists() && directory.isDirectory()) {
                for (File item : directory.listFiles()) {
                    size += getFilesSize(item);
                    size += item.length();
//                    Log.i("usableSpace==", "usableSpace=size===" + size);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return size;
        }
    }
}
